package stream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author MyPC
 * @date 2018/7/4
 */

public class StreamUtils {

    public static final String CHARSET_NAME = "UTF-8";

    public static String readSteram(InputStream inputStream) {
        try {
            byte[] bytes = new byte[1024 * 8];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len, CHARSET_NAME));
            }
            System.out.println("get message from client: " + sb);
            inputStream.close();
            return sb.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 写入一条消息
     *
     * @param outputStream 流
     * @param message      消息
     */
    public static void writeStream(OutputStream outputStream, String message) {
        try {
            outputStream.write(message.getBytes(CHARSET_NAME));
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
